package summer.student.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import summer.student.Dao.*;
import summer.student.Domain.*;
import summer.student.Utils.Judge;
import summer.student.Utils.Result;

import javax.swing.text.Style;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: student
 * @description:
 * @author: hlt
 * @create: 2023-07-08 22:19
 **/
@RestController
@RequestMapping("/teachers")
@CrossOrigin(origins = "*", maxAge = 3600)  // 后端解决跨域
@Api(tags = "教师管理相关接口")
public class TeacherController {
    @Autowired
    private TeacherDao teacherDao;

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private SelectCourseDao selectCourseDao;

    @Autowired
    private ClassDao classDao;

    @Autowired
    private CourseDao courseDao;
 
    @PostMapping("/login")
    public Result teacherLogin(@RequestBody Map<String, String>data){
        String teacherId = data.get("teacherId");
        String password = data.get("password");
        if (teacherId.length() > 20 || password.length() > 20) return Result.Error("数据非法");
        LambdaQueryWrapper<Teacher> tlqw = new LambdaQueryWrapper<>();
        tlqw.eq(Teacher::getTeacherId, teacherId);
        Teacher teacher = teacherDao.selectOne(tlqw);
        if(teacher == null) return Result.Error("账号或密码错误");
        if(password.equals(teacher.getPassword())) return Result.Success(teacherId);
        else return Result.Error("账号或密码错误");
    }

    @GetMapping("/selectSelf")
    public Result selectSelf(@RequestParam(name = "teacherId", required = true)String teacherId){
        LambdaQueryWrapper<Teacher> tlqw = new LambdaQueryWrapper<>();
        tlqw.eq(Teacher::getTeacherId, teacherId);
        Teacher teacher = teacherDao.selectOne(tlqw);
        if(teacher == null) return Result.ErrorWithSpecialMsg("教师信息未找到！",teacher);
        else return Result.Success(teacher);
    }

    @GetMapping("/selectMyClassList")
    public Result selectMyClassList(@RequestParam(name = "teacherId", required = true) String teacherId,
                                    @RequestParam(name = "currentPage", required = false, defaultValue = "1") int currentPage,
                                    @RequestParam(name="pageSize", required = false, defaultValue = "10") int pageSize){
        LambdaQueryWrapper<Classes> clqw = new LambdaQueryWrapper<>();
        clqw.eq(Classes::getTeacherId,teacherId);
        List<Classes> classes = classDao.selectList(clqw);
        ArrayList<ClassView> classViews = new ArrayList<>();
        // 整理传递给前端的信息
        for(Classes item : classes){
            Long courseId = item.getCourseId();
            ClassView classView = new ClassView();
            Long classId = item.getClassId();
            Course course = courseDao.selectById(courseId);
            Teacher teacher = teacherDao.selectById(item.getTeacherId());
            classView.setClassId(classId);
            classView.setCourseId(courseId);
            classView.setCourseTitle(course.getCourseTitle());
            classView.setTeacherName(teacher.getTeacherName());
            classView.setSemester(course.getSemester());
            classView.setGpa(course.getGpa());
            classView.setCredit(course.getCredit());
            classView.setClassroom(item.getClassroom());

            classViews.add(classView);
        }
        int count = classViews.size();
        Page<ClassView> classViewPage = new Page<>(currentPage, pageSize);
        classViewPage.setSize(pageSize);
        classViewPage.setCurrent(currentPage);
        classViewPage.setRecords(classViews);
        classViewPage.setTotal(count);
        classViewPage.setPages(count % pageSize == 0 ? count / pageSize : count / pageSize + 1);
        return Result.Success(classViewPage);
    }

    @GetMapping("/selectMyStudents")  // 教师根据班级Id查询自己班级的学生信息
    public Result selectMyStudents(@RequestParam(name = "classId", required = true) String classId,
                                   @RequestParam(name = "currentPage", required = false, defaultValue = "1") int currentPage,
                                   @RequestParam(name="pageSize", required = false, defaultValue = "10") int pageSize){
        Page<StudentsView> studentsViewPage = new Page<>();
        LambdaQueryWrapper<SelectCourse> slqw = new LambdaQueryWrapper<>();
        slqw.eq(SelectCourse::getClassId, classId);
        List<SelectCourse> selectCourses = selectCourseDao.selectList(slqw);
        ArrayList<StudentsView> studentsViews = new ArrayList<>();

        for(SelectCourse s : selectCourses){
            Student student = studentDao.selectById(s.getStuId());
            StudentsView studentsView = new StudentsView();
            studentsView.setScore(s.getScore());
            studentsView.setStuId(student.getStuId());
            studentsView.setStuName(student.getStuName());
            studentsViews.add(studentsView);
        }
        int count = studentsViews.size();
        studentsViewPage.setRecords(studentsViews);
        studentsViewPage.setPages(count % pageSize == 0 ? count / pageSize : count / pageSize + 1);
        studentsViewPage.setTotal(count);
//        studentsViewPage.setSize(pageSize);
//        studentPage.setRecords(students);
//        studentPage.setSize(pageSize);
//        studentPage.setCurrent(currentPage);
//        studentPage.setTotal(count);
//        studentPage.setPages(count % pageSize == 0 ? count / pageSize : count / pageSize);
        return Result.Success(studentsViewPage);
    }

    @PostMapping("/setScore")
    public Result setScore(@RequestBody Map<String, String> data){
        String classId = data.get("classId");
        String stuId = data.get("stuId");
        double score = Double.parseDouble(data.get("score"));
        if (classId == null || stuId == null) return Result.Error("信息不完整或信息有误！");
        if (score < 0 || score > 100) return Result.Error("score数据不合法！");
        LambdaQueryWrapper<SelectCourse> slqw = new LambdaQueryWrapper<>();
        slqw.eq(SelectCourse::getStuId,stuId).eq(SelectCourse::getClassId, classId);
        SelectCourse selectCourse = selectCourseDao.selectOne(slqw);
        if (selectCourse == null) return Result.Error("选课信息未找到！");
        selectCourse.setScore(score);
        selectCourseDao.update(selectCourse, slqw);
        return Result.Success("成绩录入成功！");
    }

    @PostMapping("/deleteClass")  // 教师删除班级
    public Result deleteClass(@RequestBody Map<String, String>data){
        if(data.get("classId") == null || data.get("classId") == "") return Result.Error("数据缺少！");
        System.out.println("classId: "+ data.get("classId"));
        long classId = Long.parseLong(data.get("classId"));
        LambdaQueryWrapper<Classes> classLQW = new LambdaQueryWrapper<>();
        classLQW.eq(Classes::getClassId,classId);
        Classes classes = classDao.selectOne(classLQW);
        if(classes == null){
            return Result.Error("未查询到班级信息！");
        }
        System.out.println(classId);
        LambdaQueryWrapper<SelectCourse> slqw = new LambdaQueryWrapper<>();
        slqw.eq(SelectCourse::getClassId, classId);
        List<SelectCourse> selectCourses = selectCourseDao.selectList(slqw);
        int result = 0;
        if (selectCourses.size() != 0) return Result.Error("已有学生选课，请联系管理员处理！");
        else{
//            result = classDao.deleteById(classId);
            result = classDao.delete(classLQW);
        }
        System.out.println(result);
        if (result != 1) {
            System.out.println("data中的classId: " + data.get("classId"));
            System.out.println("classId: " + classId);
            System.out.println("根据前端传递的参数查询班级信息：" + classes);
            return Result.Error("未知原因的删除失败，请查看日志！");
        }
        return Result.Success("删除班级成功！");
    }
}
